import React, { Component } from 'react';
import { Form, Input, Button, Icon, message } from 'antd';
import { Link } from 'react-router-dom';
import './index.less';
import { sendPassMsg, getTelbyName, resetPassword } from '../services/servicesAccount';
const FormItem = Form.Item;

class ModifyPwd extends Component {
  constructor(props) {
    super(props);
    this.state = {
      confirmDirty: false,
      visible: false,
      autoCompleteResult: [],
      checked: true,
      registerMark: '确认修改',
      getCode: '获取验证码',
      mobile: '',
    };
  }
  gotologin = () => {
    window.history.replaceState({}, null, '/');
  }
  handleOk = () => {
    this.setState({ visible: false });
  }
  handleCancel = () => {
    this.setState({ visible: false });
  }
  handleSubmit = (e) => {
    e.preventDefault();
    const telPhone = this.state.mobile;
    this.props.form.validateFieldsAndScroll((err, values) => {
      var data = {
        attr2: values.oldpassword,
        telPhone: telPhone,
        attr1: values.attr1,
        password: values.confirmpassword,
        username: values.inputusername
      };
      if (!err) {
        this.viodClickAgain('提交中...');
        this.ResetPassword(data);
      } else {
        console.log('Received values of form: ', values);
      }
    });
  }
  compareToFirstPassword = (rule, value, callback) => {
    const form = this.props.form;
    if (value && value !== form.getFieldValue('newpassword')) {
      callback('您输入的两个密码不一致');
    } else {
      callback();
    }
  }
  validateToNextPassword = (rule, value, callback) => {
    const form = this.props.form;
    if (value && form.getFieldValue('confirmpassword')) {
      form.validateFields(['confirmpassword'], { force: true });
    }
    callback();
  }
  // 按钮文字改变
  viodClickAgain = (values) => {
    this.setState({
      registerMark: values
    });
  }
  handleCode = () => {
    const mobile = this.state.mobile;
    const myreg = /^1[0-9]{10}$/;
    if (!myreg.test(mobile)) {
      message.warning('请输入正确的手机号');
    } else if (this.state.getCode !== '获取验证码') {
      return false;
    } else {
      this.SendPassMsg(mobile);
    }
  }
  getMobile = (e) => {
    const data = { username: e.target.value };
    this.GetTelbyName(data);
  }
  // 发送验证码
  async SendPassMsg(data) {
    let sec = 60;
    const response = await sendPassMsg(data);
    if (response) {
      if (response.code == '201') {
        message.warning('请输入正确的手机号');
      } else if (response.code == '202') {
        message.warning('获取手机验证码失败');
      } else if (response.code == '200') {
        const timer = setInterval(() => {
          sec--;
          if (sec < 0) {
            clearInterval(timer);
            this.setState({
              getCode: '获取验证码',
            });
          } else {
            this.setState({
              getCode: sec + 's 后重新获取',
            });
          }
        }, 1000);
      }
    }
  }
  // 获取手机号
  async GetTelbyName(data) {
    const response = await getTelbyName(data);
    if (response) {
      if (response.code == 200) {
        this.setState({
          mobile: response.data
        });
      } else if (response.message) {
        message.warning(response.message);
      }
    }
  }
  // 修改提交
  async ResetPassword(data) {
    const response = await resetPassword(data);
    this.viodClickAgain('确认修改');
    if (response) {
      if (response.code == 200) {
        message.success(response.message);
        setTimeout(() => {
          window.location.hash = '/';
        }, 1000);
      } else if (response.message) {
        message.warning(response.message);
      }
    }
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const disabledOrNot = this.state.checked ? 'primary' : 'default';
    const disabled = (this.state.checked) && (this.state.registerMark == '确认修改') ? '' : 'disabled';
    const getCodeBtn = this.state.getCode !== '获取验证码' ? 'disab getCodeBtn' : 'getCodeBtn';

    return (
      <div className="registerBox">
        <div className="img_bg">
          <div className="logo_bg">
            <a href="https://www.sinochembaas.com/" target="_blank">
              <img src={require('../Login/img/logo.png')} alt="" className="login_logo" />
            </a>
            <img src={require('../Login/img/bg.png')} alt="" className="login_bg" />
          </div>
        </div>
        <div className="form_r">
          <Form className="registerForm" onSubmit={this.handleSubmit}>
            <div className="registerCt">
              <h3 className="registerCtTop">修改密码</h3>
              <p className="modifyNotes">尊敬的用户！您的密码已过期，请修改密码后登录，谢谢！</p>
              <FormItem>
                {getFieldDecorator('inputusername', {
                  rules: [{ required: true, message: '请输入用户名' }],
                })(
                  <Input size="large" prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} className="signInput" placeholder="请输入用户名" onBlur={this.getMobile} />
                )}
              </FormItem>
              <FormItem>
                <Input size="large" prefix={<Icon type="phone" style={{ color: 'rgba(0,0,0,.25)' }} />} type="text" className="signInput" disabled value={this.state.mobile} />
              </FormItem>
              <FormItem>
                {getFieldDecorator('attr1', {
                  rules: [{ required: true, message: '请输入短信验证码，仅限数字', pattern: /^[0-9]+$/ }],
                })(
                  <div className="getCodeBox">
                    <Input size="large" prefix={<Icon type="message" style={{ color: 'rgba(0,0,0,.25)' }} />} type="text" className="signInput" placeholder="请输入短信验证码" maxLength={8} />
                    <span className={getCodeBtn} onClick={this.handleCode}>{this.state.getCode}</span>
                  </div>
                )}
              </FormItem>
              <FormItem>
                {getFieldDecorator('oldpassword', {
                  rules: [{
                    required: true, message: '请输入旧密码',
                  }, {
                    validator: this.validateToNextPassword,
                  }],
                })(
                  <Input size="large" prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} type="password" placeholder="请输入旧密码" className="signInput" maxLength={20} />
                )}
              </FormItem>
              <FormItem>
                {getFieldDecorator('newpassword', {
                  rules: [{
                    required: true, message: '请输入8到20个字符之间的字母、数字和符号组合密码', pattern: /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,20}$/
                  }, {
                    validator: this.validateToNextPassword,
                  }],
                })(
                  <Input size="large" prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} type="password" placeholder="请输入新密码" className="signInput" maxLength={20} />
                )}
              </FormItem>
              <FormItem>
                {getFieldDecorator('confirmpassword', {
                  rules: [{
                    required: true, message: '请再次设置新的登录密码',
                  }, {
                    validator: this.compareToFirstPassword,
                  }],
                })(
                  <Input size="large" prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} type="password" placeholder="确认新的登录密码" className="signInput" />
                )}
              </FormItem>
              <Button size="large" htmlType="submit" type={disabledOrNot} disabled={disabled} className="modifyBtn">{this.state.registerMark}</Button>
              <span className="loginBtn">返回<Link to="/"><em onClick={this.gotologin}>登录页面</em></Link></span>
            </div>
          </Form>
        </div>
      </div>
    );
  }
}

const ForgetPwd = Form.create()(ModifyPwd);
export default ForgetPwd;